import 'package:enterprise_v6_app/app/core/constans/dict_data_info.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_nodes_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/process_exec_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/process_vetting_entity.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/process_execution/detail/ctrl.dart';

class ProcessVettingCtrl extends GetxController {
  final entity = Get.arguments as ProcessExecEntity?;

  String? opinion;
  String? signUrl;

  /// 审批流程数据
  List<ProcessNodesEntity>? nodeList;

  /// 获取审批记录
  ///
  /// ```json
  /// {
  ///    "head": [
  ///      {
  ///        "label": "测试1",
  ///        "field": "hy_AZYIFrML",
  ///        "type": "select",
  ///        "config": {
  ///          "dictionaryTableId": "01fed771-b629-4256-bec2-3143c927e6da",
  ///          "dictionaryTableType": "pxfs_PLD6Bmp1"
  ///        }
  ///      },
  ///      {
  ///        "label": "测试",
  ///        "field": "hy_rycabSrJ",
  ///        "type": "text",
  ///        "config": null
  ///      },
  ///    ],
  ///    "data": [
  ///      {
  ///        "hy_iRKkOIOq": {
  ///          "value": "2023-12-14",
  ///          "id": "476b9593-91bd-4eb2-bb39-50b7c65d4725",
  ///          "processId": "1c9778fd-5e0f-489d-bc8a-a4a98ca5fd11",
  ///          "dictionaryTableId": null
  ///        },
  ///        "hy_CzEKMSHT": {
  ///          "value": "",
  ///          "id": "982697b3-5b10-444a-829d-13a08139615b",
  ///          "processId": "1c9778fd-5e0f-489d-bc8a-a4a98ca5fd11",
  ///          "dictionaryTableId": null
  ///        },
  ///      }
  ///    ]
  ///  }
  /// ```
  Future<List<Map<String, String>>> getVetting(int idx, int size, {String? search}) async {
    final resp = await HttpUtil().generateGetRequest<List<ProcessVettingEntity>>(
      '${Interface.mainBaseUrl}/process//approvalBusiness/approverPage',
      queryParameters: {
        'pageNum': idx,
        'pageSize': size,
        'rTemplateId': entity?.rtemplateId,
        'userId': entity?.submitUserId,
      },
    ).execute();
    final result = <Map<String, String>>[];

    /// 如果 data 为空，说明没数据
    if (resp.data == null || resp.data?.isEmpty == true) return result;

    /// 整个分页只有一条数据
    final vetting = resp.data!.first;
    if (vetting.data?.isEmpty == true) return result;

    final headMap = <String?, String?>{};

    /// 从 head 里获取数据，将数据写入 headMap {"headId" : "headName"}
    for (final item in vetting.head ?? <ProcessVettingHead>[]) {
      final headType = item.config == null;
      switch (headType) {
        /// 如果 config 不为空，说明是字典类型
        case false:
          final dictType = item.config?.dictionaryTableType;
          if (dictType == null) {
            // 暂时这样处理
            headMap[item.field] = item.label;
            break;
          }
          final dictData = await DictDataInfo.getDictionaryDataByTree(
            dictionaryType: dictType,
            isTree: false,
          );

          /// 获取 dictId 相等的数据
          final dict = dictData.firstWhereOrNull(
            (e) => e.dictionaryId == item.config?.dictionaryTableId,
          );
          headMap[item.field] = dict?.dictionaryLabel;
          break;

        /// 为空直接从 label 里获取
        default:
          headMap[item.field] = item.label;
          break;
      }
    }

    /// 解析完 head，开始解析 data
    for (final dataRaw in vetting.data ?? []) {
      final map = <String, String>{};
      final data = <String, ProcessVettingData>{};

      /// 因为是 data 的 key 动态的，所以得手动解析
      for (final key in (dataRaw as Map<String, dynamic>).keys) {
        final val = dataRaw[key];
        if (val != null) data[key] = ProcessVettingData.fromJson(val as Map<String, dynamic>);
      }
      for (final key in data.keys) {
        /// 根据 data 的 key 从 headMap 里获取对应的 headName
        final mapKey = headMap[key] ?? '';
        final val = data[key]?.value;
        if (val != null) map[mapKey] = val;
      }
      result.add(map);
    }
    return result;
  }

  /// 获取审批节点（历史记录）
  Future<void> getVettingNodes() async {
    final res = await HttpUtil().generateGetRequest<List<ProcessNodesEntity>>(
      '${Interface.mainBaseUrl}/process//approvalHistory/getHistory',
      queryParameters: {
        'rtTemplateId': entity?.rtemplateId,
      },
    ).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        nodeList = result.data!;
        update();
      }
    });
  }

  /// 提交审批
  Future<void> submit(int val) async {
    final resp = await HttpUtil().generateGetRequest(
      '${Interface.mainBaseUrl}/process//approvalBusiness/execute',
      queryParameters: {
        'rTemplateId': entity?.rtemplateId,
        'reject': val != 1,
        'comments': opinion,
        'signatureAddress': signUrl,
      },
    ).execute();
    resp.onSuccess((result) {
      Get.back(result: true);
      Get.find<ProcessExecListCtrl>().getPages();
    });
  }

  @override
  void onInit() {
    super.onInit();
    getVettingNodes();
  }
}
